package pl.flight2013.security;    

import java.io.Serializable;

import javax.ejb.Stateful;
import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.security.Authenticator;
import org.jboss.seam.security.BaseAuthenticator;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.picketlink.idm.api.Role;
import org.picketlink.idm.impl.api.PasswordCredential;
import org.picketlink.idm.impl.api.model.SimpleUser;

import pl.flight2013.entity.Users;

@Named("auth")    // ff
@Stateful 
@ConversationScoped
public class AuthBean extends BaseAuthenticator implements Authenticator, Serializable {
	@Inject
	Identity identity;
	@Inject
	Credentials credentials;  
	@PersistenceContext
	EntityManager em;

	private static final long serialVersionUID = 1L;

	@Override
	public void authenticate() {
		try {

			if ((credentials.getUsername() == null) || (credentials.getCredential() == null)) {
				// messages.error(new
				// DefaultBundleKey("identity_loginFailed")).defaults("Invalid username or password");
				setStatus(AuthenticationStatus.FAILURE);
				
			}
			Users user = (Users) em.createQuery("from Users where username = :user").setParameter("user", credentials.getUsername().toLowerCase()).getSingleResult();
			if (user != null && credentials.getCredential() instanceof PasswordCredential && user.getPassword().equals(((PasswordCredential) credentials.getCredential()).getValue())) {
				// loginEventSrc.fire(user);
				// messages.info(new DefaultBundleKey("identity_loggedIn"),
				// user.getName()).defaults("You're signed in as {0}").params(user.getName());
//				if(user.getRoles()!= null && user.getRoles().size()>0){
//					System.out.println("ustawienie roli "+user.getRoles().toString());
					System.out.println("Ustawiam role..." + identity.getRoles().size());
					for (Role role : identity.getRoles()) {
						System.out.println("---"+role.getRoleType().getName());
					}
//				}
				if("admin".equals(credentials.getUsername())){
					identity.addRole("admin", "aaa", "bbb");
				}
				
				System.out.println("Zalogowano " + credentials.getUsername());
				setStatus(AuthenticationStatus.SUCCESS);
				setUser(new SimpleUser(user.getUsername()));
				System.out.println(credentials.getUsername() + getStatus().toString());
				return;
			}

			// messages.error(new
			// DefaultBundleKey("identity_loginFailed")).defaults("Invalid username or password");
			setStatus(AuthenticationStatus.FAILURE);
			System.out.println("!!!! "+getStatus().toString());
		} catch (Exception e) {
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Błąd logowania do systemu."));
			System.out.println("Błąd logowania " + credentials.getUsername());
			setStatus(AuthenticationStatus.FAILURE);
			System.out.println("!!!! "+getStatus().toString());
		}
	}
	

}